<?php
/**
 * Created by PhpStorm.
 * User: maskerj
 * Date: 2017/8/30
 * Time: 下午2:31
 * 域名管理控制器
 */
class Domains extends MY_Controller{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @param int $code
     * @param  string $msg
     * 返回json数据
     */
    public function reJson($code,$msg)
    {
        $data = array(
            'code' => $code,
            'msg'  => $msg
        );
        echo json_encode($data);
        die();
    }
    //加载添加页面
    public function addDomains()
    {
        $this->display('domains/add_domains.html');
    }
    //获取组列表
    public function getGroupList()
    {
        $this->load->model('domains_model');
        $re = $this->domains_model->getGroupList();
        echo json_encode($re);
    }
    //接口:添加数据
    public function addData()
    {
        $data = $this->input->post();
        if(!isset($data['id_group']))
        {
            $this->reJson(0,'必须选择一个组!');
        }
        $this->load->model('domains_model');
        $domain_type = $data['domain_type'];//域类型
        if($domain_type == 'domain_reverse_ipv6')//处理ipv6
        {
            $ipv6_network = $data['ipv6_network'];//ipv6网络
            if(!filter_var($ipv6_network,FILTER_VALIDATE_IP,FILTER_FLAG_IPV6))
            {
                $this->reJson(0,'提供的地址不是有效的IPv6地址。');
            }
            //分割字符串
            $matches = explode("/",$ipv6_network);
            if(!empty($matches[0]) && !empty($matches[1]))
            {
                $v6_network = $matches[0];
                $v6_cidr = $matches[1];
                // check CIDR
                if ($v6_cidr > 128 || $v6_cidr < 1)
                {
                    $this->reJson(0,'无效的CIDR，IPv6 CIDRs / 0 / 128之间');
                }
            }
            if(empty($matches[1]))
            {
                $v6_cidr = 48;
            }
            //整理ipv6的name格式
            $domain_name = self::_ipv6ConvertArpa($v6_network.'/'.$v6_cidr);
            $id = self::_verifyDomainName($domain_name);
            if($id)
            {
                $this->reJson(0,'您要添加的请求域已经存在!');
            }
            $re = $this->domains_model->add($data,$domain_name);
            if($re != false)
            {
                $this->reJson(1,'添加成功');
            }else
            {
                $this->reJson(0,'添加失败,请稍后重试');
            }
        }elseif($domain_type=='domain_standard')//处理标准域
        {
            $domain_name = $data['domain_name'];//域名
            $id = self::_verifyDomainName($domain_name);
            if($id)
            {
                $this->reJson(0,'您要添加的请求域已经存在!');
            }
            $re = $this->domains_model->add($data,$domain_name);
            if($re != false)
            {
                $this->reJson(1,'添加成功');
            }else
            {
                $this->reJson(0,'添加失败,请稍后重试');
            }
        }elseif($domain_type == 'domain_reverse_ipv4')//处理ipv4
        {
            $matches = explode('/',$data['ipv4_network']);
            if(!empty($matches[0]) && !empty($matches[1]))
            {
                $data['ipv4_cidr'] = $matches[1];
                if($data['ipv4_cidr'] > 24)
                {
                    $this->reJson(0,'CIDRs大于/ 24不能用于反向域');
                }
            }else
            {
                $data['ipv4_cidr'] = 24;
            }
            $data['ipv4_network'] = $matches[0];
            //检测ipv4的格式是否正确
            self::_ipv4Name($data['ipv4_network'].'/'.$data['ipv4_cidr']);//测试通过
            if(isset($data['ipv4_autofill']))
            {
                if(empty($data['ipv4_autofill_domain']))
                {
                    $this->reJson(0,'必须提供域才能使用自动填充');
                }
            }
            if(isset($data['ipv4_autofill_forward']))
            {
                if(!isset($data['ipv4_autofill']))
                {
                    $this->reJson(0,'如果需要,请选择自动填充');
                }
                if(empty($data['ipv4_autofill_domain']))
                {
                    $this->reJson(0,'请填写域名');
                }
                //检测域是否可用
                $id = self::_verifyDomainName($data['ipv4_autofill_domain']);
                if($id>0)
                {
                    $data['domain_id'] = $id;
                }else
                {
                    $this->reJson(0,'域设置不存在，不能用于自动转发');
                }
            }
            // 如果 没有描述 则默认描述信息
            if (!$data["domain_description"])
            {

                $data["domain_description"] = "Reverse domain for range ".$matches[0]."/".$data['ipv4_cidr'];
            }
            $temp = explode('.',$data['ipv4_network']);
            $id = self::_verifyDomainName($temp[2].'.'.$temp[1].'.'.$temp[0].'.in-addr.arpa');
            if($id>0)
            {
                $this->reJson(0,'请求的IP范围已经有反向的DNS条目');
            }
            $re = $this->domains_model->addIpv4($data);
            if($re === false)
            {
                $this->reJson(0,'添加域失败');
            }else
            {
                $this->reJson(1,'添加域成功');
            }
        }
    }
    //加载域列表页面
    public function dnsList()
    {
        $this->display('domains/domains_list.html');
    }
    //接口:获取域列表数据
    public function getDnsList()
    {
        $page = $this->input->get('page');
        $pagesize = $this->input->get('pagesize');
        $this->load->model('domains_model');
        $rows = $this->domains_model->getDomainsList($page,$pagesize);
        echo json_encode($rows);
    }
    //加载详情页面/修改页面
    public function seeDetails()
    {
        $this->display('domains/domains_details.html');
    }
    //接口:根据id获取数据详情
    public function getDnsDetails()
    {
        $id = $this->input->get('id');
        $this->load->model('domains_model');
        $row = $this->domains_model->getIdData($id);
        //获取域的组id
        $id_group = $this->domains_model->getIdGroup($id);
        //获取组服务器列表
        $this->load->model('Servergroup_model','group');
        $group = $this->group->getGroupList(1,999);
        $data = array('domains'=>$row ,'group'=>$group['group'],'id_group'=>$id_group);
        echo json_encode($data);
    }
    //接口:更新数据
    public function updateData()
    {
        $data = $this->input->post();
        $domain_name = $data['domain_name'];//域名
        $domain_description = $data['domain_description'];//描述
        $soa_hostmaster = $data['soa_hostmaster'];//电邮管理地址
        $soa_serial = $data['soa_serial'];//域序列号
        $soa_refresh = $data['soa_refresh'];//刷新定时器
        $soa_retry = $data['soa_retry'];//刷新重试超时
        $soa_expire = $data['soa_expire'];//到期定时器
        $soa_default_ttl = $data['soa_default_ttl'];//默认记录ttl
        $group_id = $data['id_group'];
        //重新整理数据
        $updateData = array(
            'id' => $data['id'],
            'domain_name' => $domain_name,
            'domain_description' => $domain_description,
            'soa_hostmaster' => $soa_hostmaster,
            'soa_serial' => $soa_serial,
            'soa_refresh' => $soa_refresh,
            'soa_retry' => $soa_retry,
            'soa_expire' => $soa_expire ,
            'soa_default_ttl' => $soa_default_ttl
        );
        $this->load->model('domains_model');
        $result = $this->domains_model->updateIdData($updateData,$group_id);
        if($result === false)
        {
           $this->reJson(0,'修改失败,请稍后重试');
        }else
        {
            $this->reJson(1,'修改成功');
        }
    }
    //接口:根据主键删除数据
    public function delData()
    {
        $id = $this->input->get('id');
        $this->load->model('domains_model');
        $result = $this->domains_model->delIdData($id);
        if($result === false)
        {
           $this->reJson(0,'删除失败,请稍后重试!');
        }else
        {
            $this->reJson(1,'删除成功!');
        }
    }

    /**
     * @param $domain_name
     * @return int
     * 检测域名是否存在
     */
    private function _verifyDomainName($domain_name)
    {
        $this->load->model('domains_model');
        $data = $this->domains_model->getWhere("domain_name ='$domain_name'");
        if(empty($data))
        {
            return 0;
        }else
        {
            return $data[0]['id'];
        }

    }
    //检测ipv4地址的格式是否正确
    private  function _ipv4Name($name)
    {
        $reg = '/^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}[\/]*[1-9]*$/';
        if(!preg_match($reg,$name))
        {
            $this->reJson(0,'请输入有效的ipv4地址');
        }
        return $name;
    }
    //整理ipv6的name值
    private function _ipv6ConvertArpa($ipaddress)
    {
        if (preg_match("/^([0-9a-f:]*)\/([0-9]*)$/i", $ipaddress, $matches))
        {
            $cidr		= $matches[2];
            $addr		= inet_pton($matches[1]);
            $unpack		= unpack('H*hex', $addr);
            $hex		= $unpack['hex'];
            $hex_array	= str_split($hex);

            for ($i=0; $i < ($cidr / 4); $i++)
            {
                $hex_array2[$i] = $hex_array[$i];
            }

            $result		= implode('.', array_reverse($hex_array2)) . '.ip6.arpa';
        }
        else
        {
            $addr	= inet_pton($ipaddress);
            $unpack	= unpack('H*hex', $addr);
            $hex	= $unpack['hex'];
            $result	= implode('.', array_reverse(str_split($hex))) . '.ip6.arpa';
        }
        return $result;
    }
    /**
     * 测试方法
     */
    public function test()
    {
        $arr= [
            [
                'name'=>'ceshi1',
                'age' => 11
            ],
            [
            'name'=>'ceshi2',
            'age' => 12
            ],
            [
                'name'=>'ceshi3',
                'age' => 13
            ]
        ];
        $this->load->model('domains_model');
        $this->domains_model->test('nihao',$arr);
    }
}